package com.mp.core.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @author jack
 */
public class Utils {

    private static final String UNKNOWN = "unknown";

    private static final String COMMA = ",";

    /**
     * 验证带区号的
     */
    private Pattern p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");

    /**
     * 验证没有区号的
     */
    private Pattern p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");

    /**
     * 获取字符串长度
     *
     * @param value
     * @return
     */
    public static Integer getStringLeng(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 判断数组是否为空
     * ben
     *
     * @param objects
     * @return
     */
    public static boolean isNull(Object[] objects) {
        if (objects != null && objects.length > 0) {
            for (Object object : objects) {
                if (object == null) {
                    return true;
                }
                if ("".equals(object)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断list 是否为空
     *
     * @param list
     * @return
     */
    public static boolean isNull(List<Object> list) {
        try {
            if (list == null || list.isEmpty()) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("list 不能直接赋值 null");
            return true;
        }
        return false;
    }

    /**
     * 判断 list 是否补位空
     *
     * @param list
     * @return
     */
    public static boolean isNotNull(List<?> list) {
        try {
            if (list != null || !list.isEmpty()) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("list 不能直接赋值 null");
            return false;
        }
        return false;
    }

    /**
     * 验证手机号
     *
     * @param phone
     * @return boolean 验证通过返回true
     */
    @SuppressWarnings("null")
    public static boolean isPhone(String phone) {
        boolean isMatch;
        String regex = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
        switch (phone.length()) {
            case 11:
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(phone);
                isMatch = matcher.matches();
                break;
            default:
                isMatch = false;
                break;
        }
        return isMatch;
    }

    /**
     * 校验密码格式（8位，字母数字混搭）
     *
     * @param pwd
     * @return
     */
    public static boolean checkPwdFormat(String pwd) {
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$";
        if (!pwd.matches(regex)) {
            return false;
        }
        return true;
    }

    /**
     * 产生随机的四位数
     *
     * @return
     */
    public static String getfourRandomNum() {
        Random rad = new Random();
        return rad.nextInt(10000) + "";
    }

    /**
     * 验证起点ID
     *
     * @param qdid
     * @return
     */
    public static boolean checkQdid(String qdid) {
        String ruleQdid = "^[a-zA-Z_]\\w{5,19}$";
        //正则表达式的模式
        Pattern p = Pattern.compile(ruleQdid);
        //正则表达式的匹配器
        Matcher m = p.matcher(qdid);
        //进行正则匹配
        return m.matches();
    }

    /**
     * 验证密码 8-16位
     *
     * @param password
     * @return
     */
    public static boolean checkPassword(String password) {
        String rulePassword = "^[\u4e00-\u9fa5]+$";
        //正则表达式的模式
        Pattern p = Pattern.compile(rulePassword);
        //正则表达式的匹配器
        Matcher m = p.matcher(rulePassword);
        //进行正则匹配
        if (m.matches()) {
            return false;
        }
        //长度匹配
        return password.length() >= 8 && password.length() <= 16;
    }

    /**
     * 正则表达式校验邮箱
     *
     * @param emaile 待匹配的邮箱
     * @return 匹配成功返回true 否则返回false;
     */
    public static boolean checkEmaile(String emaile) {
        String rulleEmail = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
        //正则表达式的模式
        Pattern p = Pattern.compile(rulleEmail);
        //正则表达式的匹配器
        Matcher m = p.matcher(emaile);
        //进行正则匹配
        return m.matches();
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^(1)\\d{10}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 获取32位uuid
     *
     * @return
     */
    public static String get32UUid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取随机16位uuid
     *
     * @return
     */
    public static String get16UUid() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        uuid = uuid.substring(0, 16);
        return uuid;
    }

    /**
     * 获取随机6位uuid
     *
     * @return
     */
    public static String get6UUid() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        uuid = uuid.substring(0, 6);
        return uuid;
    }

    /**
     * 获取当前时间
     *
     * @return java.lang.String
     */
    public static String getCurrDate() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return simpleDateFormat.format(date);
    }

    /**
     * 获取用户ip
     *
     * @param request
     * @return java.lang.String
     * @author BuK
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(COMMA)) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

    /**
     * 获取String真实长度
     *
     * @param str
     * @return
     */
    public static int getStringRealLength(String str) {
        String s = null;
        try {
            s = new String(str.getBytes("GB2312"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s.length();
    }


    public static String getA_zBySize(int size) {
        char[] A_z = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        Random r = new Random();
        String str = "";
        int i = 0;
        while (i < size) {
            int sub = r.nextInt(A_z.length);
            str = str + A_z[sub];
            i++;
        }

        return str;
    }

    public static void main(String[] args) {
        String a_zBySize = getA_zBySize(5);
        System.out.println(a_zBySize);
    }

}
